package com.study.spark.scala.streaming.kafka.redis

import java.util

import redis.clients.jedis.{Jedis, JedisPool, JedisPoolConfig}

/**
  * jedis工具类
  *
  * @author stephen
  * @create 2019-03-20 14:32
  * @since 1.0.0
  */
object JedisUtil {

  val address = "localhost" //redis服务器ip

  val port = 6379 //redis防火墙端口

  val AUTH = "" //redis密码，通过服务器里redis配置文件里设置

  val MAX_TOTAL = 300 //最大连接数

  val MAX_IDLE = 200 //最大空闲连接数

  //等待可用连接的最大时间，单位毫秒，默认值为-1，表示永不超时。如果超过等待时间，则直接抛出
  val MAX_WAIT = 10000
  val TIMEOUT = 10000
  //在borrow一个jedis实例时，是否提前进行validate操作；如果为true，则得到的jedis实例均是可用的；
  val TEST_ON_BORROW = true

  var jedisPool: JedisPool = _

  //Jedis连接池配置
  try {
    val config = new JedisPoolConfig()
    config.setMaxTotal(MAX_TOTAL)
    config.setMaxIdle(MAX_IDLE)
    config.setMaxWaitMillis(MAX_WAIT)
    config.setTestOnBorrow(TEST_ON_BORROW)
    //jedisPool = new JedisPool(config,redisAddr,port,TIMEOUT,AUTH);  有密码的情况
    jedisPool = new JedisPool(config, address, port, TIMEOUT);
  } catch {
    case e: Exception => e.printStackTrace()
  }


  /*从jedispool中获取jedis对象*/
  def getJedis(): Jedis = {
    if (jedisPool == null) {
      throw new NullPointerException();
    }
    return jedisPool.getResource();
  }

  def getKeys(pattern: String): util.Set[String] = {
    try {
      getJedis().keys(pattern)
    } catch {
      case e: Exception => e.printStackTrace()
        null
    }
  }

  def get(key: String): String = {
    try {
      getJedis().get(key)
    } catch {
      case e: Exception => e.printStackTrace()
        null
    }
  }

  def set(key: String, value: String) = {
    try {
      getJedis().set(key, value)
    } catch {
      case e: Exception => {
        e.printStackTrace()
      }
    }
  }


  def hmset(key: String, map: java.util.Map[String, String]): Unit = {
    try {
      getJedis().hmset(key, map)
    } catch {
      case e: Exception => e.printStackTrace()
    }
  }

  def hset(key: String, field: String, value: String): Unit = {
    try {
      getJedis().hset(key, field, value)
    } catch {
      case e: Exception => {
        e.printStackTrace()
      }
    }
  }

  def hget(key: String, field: String): String = {
    try {
      getJedis().hget(key, field)
    } catch {
      case e: Exception => e.printStackTrace()
        null
    }
  }

  def hgetAll(key: String): java.util.Map[String, String] = {
    try {
      getJedis().hgetAll(key)
    } catch {
      case e: Exception => e.printStackTrace()
        null
    }
  }
}

